// 反馈处理的函数

var constant = require('../../const');
var models = require('../../models');
var AV = require('leanengine');
/*
 * title: 获取用户反馈的页面
 */
function getFeedback(req, res) {
  if (!req.AV.user) {
    res.redirect('/admin');
  }

  //0等待处理 1 已经处理,2已经忽略
  var status = req.query.status||0;

  var query = new AV.Query(models.MLFeedback);
  if(status==0){
    query.equalTo("status",0)
  }else if(status==1){
    query.equalTo("status",1)
  }else if(status==2){
    query.equalTo("status",2)
  }
  query.include("user");
  query.descending("createdAt");
  query.limit(1000);

  query.find({
    success:function(feedbacks) {
      var data = {
        "username": req.session.username,
        "status": status,
        "feedbacks": feedbacks
      };
      res.render('admin/feedback/index', data);
    },
    error: function(error) {
      res.render('admin/feedback/index', {"username": req.session.username});
    }
  });

}

/*
 * title: 用户反馈处理的页面
 */
function getFeedbackHandler(req, res) {
  if (!req.AV.user) {
    res.redirect('/admin');
  }

  // 获取参数中得objectId
  var objectId = req.query.objectId;

  var feedbackQuery = new AV.Query(models.MLFeedback);
  feedbackQuery.include("user");

  feedbackQuery.get(objectId, {
    success: function(feedback) {

      var data = {
        "username": req.session.username,
        "feedback": feedback
      };
      console.log(data);
      res.render('admin/feedback/handler', data);

    },
    error: function(error) {
      res.render('admin/feedback/handler', {"username": req.session.username});
    }
  });
}

/*
 * title: 处理用户反馈 
 */
function handleFeedback(req, res) {
  if (!req.AV.user) {
    res.redirect('/admin');
  }
  var userId = req.body.userId;
  var content = req.body.content||"";
  var feedbackId = req.body.feedbackId;
  var feedType = req.body.feedType||0;

  var feedbackQuery = new AV.Query(models.MLFeedback);
  feedbackQuery.get(feedbackId, {
    success: function(feedback) {
      if(feedType==0){
        feedback.set("status",constant.FEEDBACK_STATUS_HANDLED);
        feedback.save();
        AV.Cloud.run('sendSysMsg', {"touserId":userId,"msg": content}, {
          success: function(result) {
            // result is 'Hello world!'
              res.send({"code":0,"msg":"发送成功"});
            },
            error: function(error) {
              res.send({"code":1,"msg":"发送失败"});
            }
        });
      }else{
        feedback.set("status",constant.FEEDBACK_STATUS_CANCEL);
        feedback.save();
        res.send({"code":0,"msg":"成功"});
      }
      
    },
    error: function(error) {
      res.send({"code":1,"msg":"发送失败"});
    }
  });
  

}



exports.getFeedback = getFeedback;
exports.getFeedbackHandler = getFeedbackHandler;
exports.handleFeedback = handleFeedback;
